package com.yupi.yuoj.judge;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.yupi.yuoj.common.ErrorCode;
import com.yupi.yuoj.exception.BusinessException;
import com.yupi.yuoj.judge.codesandbox.CodeSandbox;
import com.yupi.yuoj.judge.codesandbox.CodeSandboxFactory;
import com.yupi.yuoj.judge.codesandbox.CodeSandboxProxy;
import com.yupi.yuoj.judge.codesandbox.model.ExcuteCodeRequest;
import com.yupi.yuoj.judge.codesandbox.model.ExcuteCodeResponse;
import com.yupi.yuoj.judge.codesandbox.model.JudgeInfo;
import com.yupi.yuoj.judge.strategy.DefaultJudgeStrategy;
import com.yupi.yuoj.judge.strategy.JavaLanguageJudgeStrategy;
import com.yupi.yuoj.judge.strategy.JudgeContext;
import com.yupi.yuoj.judge.strategy.JudgeStrategy;
import com.yupi.yuoj.model.dto.question.JudgeCase;
import com.yupi.yuoj.model.dto.question.JudgeConfig;
import com.yupi.yuoj.model.entity.Question;
import com.yupi.yuoj.model.entity.QuestionSubmit;
import com.yupi.yuoj.model.enums.JudgeInfoMessageEnum;
import com.yupi.yuoj.model.enums.QuestionSubmitStatusEnum;
import com.yupi.yuoj.model.vo.QuestionSubmitVO;
import com.yupi.yuoj.service.QuestionService;
import com.yupi.yuoj.service.QuestionSubmitService;
import org.elasticsearch.Assertions;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;


import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
@Service
public class JudgeServiceImpl implements JudgeService {
    //判题服务需要做的事情
    //1）传入题目的提交 id，获取到对应的题目、提交信息（包含代码、编程语言等）
    //2）如果题目提交状态不为等待中，就不用重复执行了
    //3）更改判题（题目提交）的状态为 “判题中”，防止重复执行，也能让用户即时看到状态
    //4）调用沙箱，获取到执行结果
    //5）根据沙箱的执行结果，设置题目的判题状态和信息
    @Resource
    private QuestionService questionService;
    @Resource
    private QuestionSubmitService questionSubmitService;
    @Resource
    private JudgeManager judgeManager;

    @Value("${codesandbox.type:example}")
    private String type;

    @Override
    public QuestionSubmit doJudge(long questionSubmitId) {
        QuestionSubmit questionSubmit = questionSubmitService.getById(questionSubmitId);
        if(questionSubmit == null){
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR,"提交的信息不存在");
        }
        Long questionId = questionSubmit.getQuestionId();
        Question question = questionService.getById(questionId);
        if(question == null){
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR,"题目不存在");
        }
        Integer questionSubmitStatus = questionSubmit.getStatus();
        if(!questionSubmitStatus.equals(QuestionSubmitStatusEnum.WAITING.getValue())){
            throw new BusinessException(ErrorCode.OPERATION_ERROR,"题目正在判题中");
        }
        QuestionSubmit questionSubmitUpdate = new QuestionSubmit();
        questionSubmitUpdate.setId(questionSubmitId);
        questionSubmitUpdate.setStatus(QuestionSubmitStatusEnum.RUNNING.getValue());
        boolean updateFlag = questionSubmitService.updateById(questionSubmitUpdate);
        if(!updateFlag){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"判题状态更新失败");
        }
        CodeSandbox codeSandbox = CodeSandboxFactory.newInstance(type);
        CodeSandboxProxy codeSandboxProxy = new CodeSandboxProxy(codeSandbox);
        ExcuteCodeRequest excuteCodeRequest = new ExcuteCodeRequest();
        String code = questionSubmit.getCode();
        String language = questionSubmit.getLanguage();
        String judgeCaseStr = question.getJudgeCase();
        List<JudgeCase> judgeCasesList = JSONUtil.toList(judgeCaseStr, JudgeCase.class);
        List<String> inputListByQuestion = judgeCasesList.stream().map(JudgeCase::getInput).collect(Collectors.toList());
        excuteCodeRequest.setInputList(inputListByQuestion);
        excuteCodeRequest.setCode(code);
        excuteCodeRequest.setLanguage(language);
        ExcuteCodeResponse excuteCodeResponse = codeSandboxProxy.excuteCode(excuteCodeRequest);
        List<String> outputListBySanbox = excuteCodeResponse.getOutputList();
        String status = excuteCodeResponse.getStatus();
        String message = excuteCodeResponse.getMessage();
        //原本如果没有java的特殊策略的化new DefaultJudgeStrategy();返回的是DefaultJudgeStrategy
        //现在多了JavaLanguageJudgeStrategy 由于返回的类型不一致导致不能复用这就是为什么要实现同一个接口了
        //现在new DefaultJudgeStrategy();返回的是JudgeStrategy 而JavaLanguageJudgeStrategy返回的也是JudgeStrategy所以可以复用
//        JudgeStrategy judgeStrategy = new DefaultJudgeStrategy();
//        if (language.equals("java")) {
//            judgeStrategy = new JavaLanguageJudgeStrategy();
//        }
        JudgeContext judgeContext = new JudgeContext();
        judgeContext.setJudgeInfo(excuteCodeResponse.getJudgeInfo());
        judgeContext.setInputList(inputListByQuestion);
        judgeContext.setOutputList(outputListBySanbox);
        judgeContext.setQuestion(question);
        judgeContext.setJudgeCasesList(judgeCasesList);
        judgeContext.setQuestionSubmit(questionSubmit);

        JudgeInfo judgeInfo = judgeManager.doJudge(judgeContext);
//        JudgeInfo judgeInfo = judgeStrategy.doJudge(judgeContext);
        //修改数据库中的判题结果
        questionSubmitUpdate = new QuestionSubmit();
        questionSubmitUpdate.setId(questionSubmitId);
        questionSubmitUpdate.setStatus(QuestionSubmitStatusEnum.SUCCEED.getValue());
        questionSubmitUpdate.setJudgeInfo(JSONUtil.toJsonStr(judgeInfo));
        boolean update= questionSubmitService.updateById(questionSubmitUpdate);
        if(!update){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"判题状态更新失败");
        }
        QuestionSubmit questionSubmitResult = questionSubmitService.getById(questionSubmitId);

        return questionSubmitResult;
    }
}
